<template>
  <div class="brand-performance-table">
    <!-- 搜索和筛选工具栏 -->
    <div class="table-toolbar">
      <div class="toolbar-left">
        <el-input
          v-model="searchForm.brandName"
          placeholder="搜索品牌名称"
          style="width: 200px;"
          clearable
          @change="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select
          v-model="searchForm.firstCategory"
          placeholder="一级类目"
          style="width: 150px;"
          clearable
          @change="handleSearch"
        >
          <el-option label="全部" value="" />
          <el-option 
            v-for="category in categoryOptions" 
            :key="category"
            :label="category" 
            :value="category" 
          />
        </el-select>

        <el-select
          v-model="searchForm.operationMode"
          placeholder="经营模式"
          style="width: 120px;"
          clearable
          @change="handleSearch"
        >
          <el-option label="全部" value="" />
          <el-option 
            v-for="mode in operationModeOptions" 
            :key="mode"
            :label="mode" 
            :value="mode" 
          />
        </el-select>

        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="resetSearch">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </div>

      <div class="toolbar-right">
        <el-button @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button type="primary" @click="emit('refresh', searchForm)">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      :loading="loading"
      stripe
      border
      style="width: 100%"
      :default-sort="{ prop: 'transactionAmount', order: 'descending' }"
      @sort-change="handleSortChange"
    >
      <el-table-column
        prop="brandName"
        label="品牌名称"
        width="140"
        fixed="left"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <div class="brand-cell">
            <div class="brand-name">{{ row.brandName }}</div>
            <div class="brand-category">{{ row.firstCategory }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        prop="operationMode"
        label="经营模式"
        width="100"
        align="center"
      >
        <template #default="{ row }">
          <el-tag
            :type="getOperationModeType(row.operationMode) as 'success' | 'info' | 'warning' | 'primary' | 'danger'"
            size="small"
          >
            {{ row.operationMode }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="pageViews"
        label="浏览量"
        width="120"
        align="right"
        sortable="custom"
      >
        <template #default="{ row }">
          {{ formatNumber(row.pageViews) }}
        </template>
      </el-table-column>

      <el-table-column
        prop="visitorCount"
        label="访客数"
        width="120"
        align="right"
        sortable="custom"
      >
        <template #default="{ row }">
          {{ formatNumber(row.visitorCount) }}
        </template>
      </el-table-column>

      <el-table-column
        prop="avgPageViewsPerVisitor"
        label="人均浏览量"
        width="120"
        align="right"
      >
        <template #default="{ row }">
          {{ formatDecimal(row.avgPageViewsPerVisitor) }}
        </template>
      </el-table-column>

      <el-table-column
        prop="avgStayTime"
        label="平均停留时长"
        width="130"
        align="right"
      >
        <template #default="{ row }">
          {{ formatTime(row.avgStayTime) }}
        </template>
      </el-table-column>

      <el-table-column
        prop="transactionUserCount"
        label="成交人数"
        width="120"
        align="right"
        sortable="custom"
      >
        <template #default="{ row }">
          {{ formatNumber(row.transactionUserCount) }}
        </template>
      </el-table-column>

      <el-table-column
        prop="conversionRate"
        label="转化率"
        width="100"
        align="right"
        sortable="custom"
      >
        <template #default="{ row }">
          <div class="rate-cell">
            <span :class="getConversionRateClass(row.conversionRate)">
              {{ formatPercentage(row.conversionRate) }}
            </span>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        prop="transactionOrderCount"
        label="成交单量"
        width="120"
        align="right"
        sortable="custom"
      >
        <template #default="{ row }">
          {{ formatNumber(row.transactionOrderCount) }}
        </template>
      </el-table-column>

      <el-table-column
        prop="transactionItemCount"
        label="成交件数"
        width="120"
        align="right"
        sortable="custom"
      >
        <template #default="{ row }">
          {{ formatNumber(row.transactionItemCount) }}
        </template>
      </el-table-column>

      <el-table-column
        prop="transactionAmount"
        label="成交金额(万元)"
        width="140"
        align="right"
        sortable="custom"
      >
        <template #default="{ row }">
          <div class="amount-cell">
            <span class="amount-value">
              {{ formatCurrency(row.transactionAmount) }}
            </span>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        prop="averageTransactionValue"
        label="客单价(元)"
        width="120"
        align="right"
        sortable="custom"
      >
        <template #default="{ row }">
          {{ formatCurrency(row.averageTransactionValue) }}
        </template>
      </el-table-column>

      <el-table-column
        prop="updateTime"
        label="更新时间"
        width="180"
        align="center"
      >
        <template #default="{ row }">
          {{ formatDateTime(row.updateTime) }}
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        width="120"
        align="center"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            text
            @click="viewDetail(row)"
          >
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-if="pagination.total > 0"
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <div v-else style="text-align: center; color: #999; padding: 20px;">
        暂无数据
      </div>
    </div>

    <!-- 品牌详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      :title="`${selectedBrand?.brandName} - 品牌详情`"
      width="60%"
    >
      <BrandDetailInfo v-if="selectedBrand" :brand-data="selectedBrand" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, Refresh, Download
} from '@element-plus/icons-vue'
import { distributionApi } from '@/api/dashboard/distribution.api'
import type { BrandPerformanceData, BrandQuery } from '@/types/distribution'
import BrandDetailInfo from './BrandDetailInfo.vue'

// Props 和 Emits
interface Props {
  data: BrandPerformanceData[]
  loading: boolean
  pagination?: { total: number; pageNum: number; pageSize: number }
}

const props = defineProps<Props>()
const emit = defineEmits<{
  refresh: [searchForm: Partial<BrandQuery>]
}>()

// 响应式数据
const searchForm = reactive<Partial<BrandQuery>>({
  brandName: '',
  firstCategory: '',
  operationMode: '',
  sortBy: 'transactionAmount',
  sortOrder: 'desc'
})

const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

const detailVisible = ref(false)
const selectedBrand = ref<BrandPerformanceData | null>(null)

// 选项数据
const categoryOptions = ref<string[]>([])
const operationModeOptions = ref<string[]>([])
const brandOptions = ref<string[]>([])

// 计算属性
const tableData = computed(() => {
  return props.data || []
})

// 加载选项数据
async function loadOptions() {
  try {
    const [categories, modes, brands] = await Promise.all([
      distributionApi.getCategoryOptions(),
      distributionApi.getOperationModeOptions(),
      distributionApi.getBrandOptions()
    ])
    
    console.log('加载的选项数据:', { categories, modes, brands }) // 调试日志
    
    categoryOptions.value = categories || []
    operationModeOptions.value = modes || []
    brandOptions.value = brands || []
  } catch (error) {
    console.error('加载选项数据失败:', error)
    ElMessage.error('加载选项数据失败，请稍后重试')
  }
}

// 工具函数
function formatNumber(num: number | null | undefined): string {
  if (num == null || isNaN(num)) return '0'
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toLocaleString()
}

function formatCurrency(num: number | null | undefined): string {
  if (num == null || isNaN(num)) return '¥0.00'
  return '¥' + num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

function formatPercentage(num: number | null | undefined): string {
  if (num == null || isNaN(num)) return '0.00%'
  return num.toFixed(2) + '%'
}

function formatDecimal(num: number | null | undefined): string {
  if (num == null || isNaN(num)) return '0.00'
  return num.toFixed(2)
}

function formatTime(seconds: number | null | undefined): string {
  if (seconds == null || isNaN(seconds)) return '0秒'
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  if (minutes > 0) {
    return `${minutes}分${remainingSeconds}秒`
  }
  return `${remainingSeconds}秒`
}

function formatDateTime(dateStr: string | null | undefined): string {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

function getOperationModeType(mode: string): string {
  const typeMap: Record<string, string> = {
    '专营店': 'primary',
    '授权店': 'success', 
    '旗舰店': 'warning',
    // 兼容旧数据
    '直营': 'success',
    '代销': 'warning',
    '经销': 'primary'
  }
  return typeMap[mode] || 'info'
}

function getConversionRateClass(rate: number | null | undefined): string {
  if (rate == null || isNaN(rate)) return 'rate-poor'
  if (rate >= 10) return 'rate-excellent'
  if (rate >= 5) return 'rate-good'
  if (rate >= 2) return 'rate-normal'
  return 'rate-poor'
}

// 业务逻辑函数
function handleSearch() {
  pagination.pageNum = 1
  // 触发父组件重新加载数据
  emit('refresh', searchForm)
}

function resetSearch() {
  Object.assign(searchForm, {
    brandName: '',
    firstCategory: '',
    operationMode: '',
    sortBy: 'transactionAmount',
    sortOrder: 'desc'
  })
  pagination.pageNum = 1
  // 触发父组件重新加载数据
  emit('refresh', searchForm)
}

function handleSortChange({ prop, order }: { prop: string; order: string | null }) {
  if (order) {
    searchForm.sortBy = prop as any
    searchForm.sortOrder = order === 'ascending' ? 'asc' : 'desc'
    // 触发父组件重新加载数据
    emit('refresh', { ...searchForm, pageNum: pagination.pageNum, pageSize: pagination.pageSize })
  }
}

function handleSizeChange(size: number) {
  pagination.pageSize = size
  pagination.pageNum = 1
  // 触发父组件重新加载数据
  emit('refresh', { ...searchForm, pageNum: pagination.pageNum, pageSize: pagination.pageSize })
}

function handleCurrentChange(page: number) {
  pagination.pageNum = page
  // 触发父组件重新加载数据
  emit('refresh', { ...searchForm, pageNum: pagination.pageNum, pageSize: pagination.pageSize })
}

function viewDetail(brand: BrandPerformanceData) {
  selectedBrand.value = brand
  detailVisible.value = true
}

async function exportData() {
  try {
    ElMessage.info('正在导出数据，请稍候...')
    
    // 构建导出参数
    const params = {
      brandName: searchForm.brandName || undefined,
      firstCategory: searchForm.firstCategory || undefined,
      operationMode: searchForm.operationMode || undefined
    }
    
    console.log('导出参数:', params) // 调试日志
    
    // 调用API导出数据，返回Blob
    const response = await distributionApi.exportBrandPerformance(params)
    
    console.log('API响应:', response) // 调试日志
    
    // 检查响应是否为Blob
    if (!(response instanceof Blob)) {
      console.error('响应不是Blob类型:', typeof response, response)
      throw new Error('服务器返回的数据格式不正确')
    }
    
    // 检查Blob是否有效
    if (response.size === 0) {
      throw new Error('导出的文件为空')
    }
    
    // 创建下载链接
    const url = window.URL.createObjectURL(response)
    const link = document.createElement('a')
    link.href = url
    link.download = `品牌表现数据_${new Date().toISOString().split('T')[0]}.xlsx`
    
    // 添加到DOM并触发下载
    document.body.appendChild(link)
    link.click()
    
    // 清理资源
    setTimeout(() => {
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    }, 100)
    
    ElMessage.success('导出成功！')
  } catch (error) {
    console.error('导出失败:', error)
    if (error instanceof Error) {
      ElMessage.error(`导出失败: ${error.message}`)
    } else {
      ElMessage.error('导出失败，请稍后重试')
    }
  }
}

// 组件挂载时设置分页总数
onMounted(() => {
  if (props.pagination) {
    // 确保total是数字类型
    pagination.total = typeof props.pagination.total === 'string' ? parseInt(props.pagination.total, 10) : (props.pagination.total || 0)
    pagination.pageNum = props.pagination.pageNum
    pagination.pageSize = props.pagination.pageSize
  }
  loadOptions()
})

// 监听props.pagination变化，更新分页信息
watch(() => props.pagination, (newPagination) => {
  if (newPagination) {
    // 确保total是数字类型
    pagination.total = typeof newPagination.total === 'string' ? parseInt(newPagination.total, 10) : (newPagination.total || 0)
    pagination.pageNum = newPagination.pageNum
    pagination.pageSize = newPagination.pageSize
    console.log('分页信息更新:', {
      total: pagination.total,
      totalType: typeof pagination.total,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    })
  }
}, { immediate: true, deep: true })
</script>

<style scoped lang="scss">
.brand-performance-table {
  .table-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .toolbar-left {
      display: flex;
      gap: 12px;
      align-items: center;
    }

    .toolbar-right {
      display: flex;
      gap: 12px;
    }
  }

  .brand-cell {
    .brand-name {
      font-weight: 600;
      color: #1f2937;
      margin-bottom: 2px;
    }

    .brand-category {
      font-size: 12px;
      color: #6b7280;
    }
  }

  .rate-cell {
    .rate-excellent {
      color: #16a34a;
      font-weight: 600;
    }

    .rate-good {
      color: #059669;
      font-weight: 600;
    }

    .rate-normal {
      color: #d97706;
      font-weight: 600;
    }

    .rate-poor {
      color: #dc2626;
      font-weight: 600;
    }
  }

  .amount-cell {
    .amount-value {
      font-weight: 600;
      color: #1f2937;
    }
  }

  .pagination-wrapper {
    display: flex !important;
    justify-content: center !important;
    padding: 20px !important;
    background: white !important;
    border-radius: 8px !important;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05) !important;
    margin-top: 16px !important;
    min-height: 60px !important;
    align-items: center !important;
    flex-direction: column !important;
  }

  :deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;

    .el-table__header-wrapper {
      .el-table__header {
        th {
          background: #f8fafc;
          color: #374151;
          font-weight: 600;
        }
      }
    }

    .el-table__body-wrapper {
      .el-table__row {
        &:hover {
          background: #f8fafc;
        }
      }
    }
  }

  @media (max-width: 768px) {
    .table-toolbar {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;

      .toolbar-left,
      .toolbar-right {
        justify-content: center;
        flex-wrap: wrap;
      }
    }
  }
}
</style> 